<?php
/**
 * 审核 优化处理Controller
 */

namespace Common\Controller;

use Common\Controller\WahahabaseController;

class AuditbaseController extends WahahabaseController
{
    // 审核记录model
    public $auditHistoryModel, $auditFlowModel, $roleuser_model, $audituser_model, $users_model;

    // 当前处理流程
    public $function, $subfunction;

    function _initialize()
    {
        parent::_initialize();
        $this->auditHistoryModel = D("common/AuditHistory");
        $this->auditFlowModel    = D("common/AuditFlow");
        $this->att_model         = D("Common/Attachment");
        $this->roleuser_model    = D("Common/RoleUser");
        $this->audituser_model   = D("Common/AuditUser");
        $this->users_model       = D("Common/Users");
        $this->getUserRole();
    }
    //分配权限继承
    public function distribution_base()
    {
        $id = I('get.id', 0, 'intval');

        $adminId = session('ADMIN_ID');
        $result  = $this->users_model->alias("u")
            ->field('u.department_id')
            ->where("u.id = '$adminId'")
            ->order("u.add_time DESC")
            ->find();
        //部门id号
        $did = $result['department_id'];
        //本单位的全部用户
        $users = $this->users_model->alias("u")
            ->field('u.real_name,u.id')
            //->join('hzzy_role_user ON u.id = hzzy_role_user.user_id')
            ->where("u.department_id ='$did'")
            ->select();

        $data = [];
        //遍历当前授权的用户
        foreach ($users as $user) {
            $user_id     = $user['id'];
            $role_user_2 = $this->roleuser_model
                ->where('user_id=' . $user_id . " and option_id=2 and code_id=" . $id . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")
                ->find();

            $role_user_3 = $this->roleuser_model
                ->where('user_id=' . $user_id . " and option_id=3 and code_id=" . $id . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")
                ->find();

            $user['is_check_2'] = 0;
            $user['is_check_3'] = 0;

            //如果是一级审核权
            if ($role_user_2) {
                $user['is_check_2'] = 1;
            }

            //如果是二级审核权
            if ($role_user_3) {
                $user['is_check_3'] = 1;
            }
            $data[] = $user;
        }

        $this->assign("users", $data);
        $this->display();
    }


    // 查询审批列表
    public function indexAuditPage($where)
    {
        // 当前登录人
        $adminId = session('ADMIN_ID');
        $adminGroup = getUserInfo($adminId);
        if($adminGroup['department_role']>3)
            $where .= " AND d.add_department='$adminGroup[department_id]'";
        //

        $user      = $this->users_model->where('id=' . session('ADMIN_ID'))->find();
        $user_role = $user['role_id'];

        $isAudit = ",(
		CASE
			WHEN audit_status = 1 and (SELECT role_id FROM " . C('DB_PREFIX') . "users WHERE id = '" . session('ADMIN_ID') . "') = '4'  THEN 4
			WHEN audit_status != 1 THEN 2
			WHEN d.audit_level = 2  AND d.add_department = " . session('deptid') . " THEN 1
			WHEN d.audit_level > 2 AND audit_status = 1 AND d.audit_level % 2 = 1 
				
					AND (
						SELECT 2 * fd.`level` + 1
						FROM " . C('DB_PREFIX') . "audit_flow_dept fd
						LEFT JOIN " . C('DB_PREFIX') . "audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '" . $this->function . "' AND f.subfunction = '" . $this->subfunction . "' AND fd.department_id = " . session('deptid') . " ) = d.audit_level
			THEN 1
			WHEN d.audit_level > 2 AND audit_status = 1 AND d.audit_level % 2 = 1 
					
					AND (
						SELECT 2 * fd.`level` + 1
						FROM " . C('DB_PREFIX') . "audit_flow_dept fd
						LEFT JOIN " . C('DB_PREFIX') . "audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '" . $this->function . "' AND f.subfunction = '" . $this->subfunction . "' AND fd.department_id = " . session('deptid') . " ) = d.audit_level
			THEN 1
			WHEN d.audit_level > 2 AND audit_status = 1 AND d.audit_level % 2 = 0
				
					AND (
						SELECT 2 * fd.`level` + 2
						FROM " . C('DB_PREFIX') . "audit_flow_dept fd
						LEFT JOIN " . C('DB_PREFIX') . "audit_flow f ON fd.flow_id = f.id
						WHERE f. FUNCTION = '" . $this->function . "' AND f.subfunction = '" . $this->subfunction . "' AND fd.department_id = " . session('deptid') . ") = d.audit_level
			THEN 1
			ELSE 2
		END
		) as isaudit";

        /* $where = $where . " AND (
             d.add_user = '" . session('ADMIN_ID') . "'
             OR 1 = '" . session('ADMIN_ID') . "'
             
         )";*/

        //数量
        $count = $this->deal_model->alias("d")
                                    ->join(array(
                                        ' LEFT JOIN ' . C('DB_PREFIX') . 'users u ON d.add_user = u.id',
                                        ' LEFT JOIN ' . C('DB_PREFIX') . 'department Com ON u.department_id = Com.id',))
                                    ->where($where)->distinct(true)->count();

        //分页
        $page = $this->page($count, 20);

        $results = $this->deal_model->alias("d")
            ->field('d.*,u.real_name,f.level,h.time,de.department_name,u1.real_name as usname,DATE_ADD(h.time, INTERVAL 7 DAY) as newtime,
						(CASE 
							WHEN d.audit_level > 2 THEN ad.department_name
							ELSE ad1.department_name
						END) as curdept' . $isAudit)
            ->join(array(
                ' LEFT JOIN ' . C('DB_PREFIX') . 'users u ON d.add_user = u.id',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'department Com ON u.department_id = Com.id',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'audit_flow f ON f.function = \'' . $this->function . "' AND f.subfunction='" . $this->subfunction . "'",
                ' LEFT JOIN (SELECT table_id,MAX(add_time) as time,add_user,add_department FROM (SELECT * FROM ' . C('DB_PREFIX') . 'audit_history WHERE `function` = \'' . $this->function . '\' AND subfunction = \'' . $this->subfunction . '\' ORDER BY id DESC) as T GROUP BY table_id) as h ON h.table_id = d.id',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'department de ON h.add_department = de.id',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'users u1 ON h.add_user = u1.id ',

                ' LEFT JOIN ' . C('DB_PREFIX') . 'audit_flow af ON af.`function` = \'' . $this->function . '\' AND af.subfunction = \'' . $this->subfunction . '\' ',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'audit_flow_dept afd ON af.id = afd.flow_id AND afd.`level` = floor((d.audit_level - 1)/2) ',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'department ad ON afd.department_id = ad.id ',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'department ad1 ON d.add_department = ad1.id ',
            ))
            ->where($where)
            ->order("d.add_time DESC")
            ->distinct(true)
            ->limit($page->firstRow, $page->listRows)
            ->select();
        //var_dump($results);
        //exit($this->deal_model->getLastSql());
        $this->assign("page", $page->show('Admin'));

        $data = [];

        foreach ($results as $value) {
            $value['edit_no'] = 1;
            $code_id          = $value['id'];

            //本条记录当前审批层级
            $value_level = $value['audit_level'];
            //审核人员的权限
            if ($user['role_id'] == 4) {
                $role_can = $this->deal_model->alias("d")->where( " afd.department_id=" . $user['department_id'])->join(array(
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'audit_flow af ON af.`function` = \'' . $this->function . '\' AND af.subfunction = \'' . $this->subfunction . '\' ',
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'audit_flow_dept afd ON af.id = afd.flow_id AND afd.`level` <= floor((d.audit_level - 1)/2) ',
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'department ad ON afd.department_id = ad.id ' . " and afd.department_id=" . $user['department_id'],
                ))->find();
//print_r($this->deal_model->getLastSql());
//print_r("<br/>");
//print_r($role_can);
//die();
                if ($role_can['id'] == null) {
                    $value['edit_no'] = 3;
                }elseif($role_can['level']>0){
                    $r_l = ($role_can['level']+1)*2;
                    if($r_l>=$value['audit_level']&&($r_l-1)<=$value['audit_level']){
                        $value['edit_no'] = 1;
                    }else{
                        $value['edit_no'] = 3;
                    }
                }else{
                    $value['edit_no'] = 3;
                }

                $d_user_ids = $this->users_model->where("department_id=" . $user['department_id'])->getField('id', true);
                
                $min_level_user = $this->roleuser_model
                    ->where(" code_id=" . $code_id . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")
                    ->where(['user_id' => ['in', $d_user_ids]])
                    ->order('audit_level asc')
                    ->find();

                if ($min_level_user) {

                    //echo '1---';
                    $min_level = $min_level_user['audit_level'];
                    //已经设置了一级审核人员
                    if ($min_level % 2 == 1) {
                        //echo '2-----';
                        $is_do = $this->roleuser_model->where("code_id=" . $code_id . " and status=1 and audit_level=" . $min_level . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")->find();
                        //分配之后已经有人操作
                        if ($is_do) {
                            $value['permission']  = 1;
                            $value['action_text'] = '查看';
                            $value['edit_no']     = 0;
                        }
                    }
                }
            }

            $user_department = $user['department_id'];
            //如果当前用户为发起公司用户
            if ($user_department == $value['add_department']) {

                //如果当前用户是审核用户
                if ($user['role_id'] == 3) {

                    //如果用户未操作审核
                    if ($value['audit_status'] == 1 && $value['audit_level'] == 2) {
                        //echo 4444;
                        $value['permission']  = 2;
                        $value['action_text'] = '审核';
                    } else if ($value['audit_status'] == 2 && $value['audit_level'] == 2) {
                        $value['permission']  = 2;
                        $value['action_text'] = '审核';
                    } else {
                        $value['permission']  = 1;
                        $value['action_text'] = '查看';
                    }
                } else {
                    $value['permission']  = 1;
                    $value['action_text'] = '查看';
                }
            }


            $role_users = $this->roleuser_model
                ->where("code_id=" . $code_id . "  and user_id=" . session('ADMIN_ID') . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")
                ->order("audit_level asc")
                ->select();
            //如果当前用户既有一级审核权限和二级审核权限

            if (sizeof($role_users) == 2) {
                //echo 4;
                //如果此人有两种权限
                //如果当前是一级审核
                if ($value_level == $role_users[0]['audit_level']) {

                    //echo '当前数据等级：'.$value['code'].',当前用户等级：'.$role_users[0]['audit_level'];
                    if ($role_users[0]['status'] == 1) {
                        $value['permission']  = 1;
                        $value['action_text'] = '查看';
                    } else {
                        $value['permission']  = 2;
                        $value['action_text'] = '一级审核';
                    }
                } else if ($value_level == $role_users[1]['audit_level']) {

                    if ($role_users[1]['status'] == 1) {
                        $value['permission']  = 1;
                        $value['action_text'] = '查看';
                    } else {
                        $value['permission']  = 2;
                        $value['action_text'] = '二级审核';
                    }
                } else {
                    //如果不在当前审核等级，有两种情况，一种是驳回的情况，比role_user中的audit_level小
                    $value['permission']  = 1;
                    $value['action_text'] = '查看';
                }
            } elseif (sizeof($role_users) == 1) {
                //echo 5;
                if ($role_users[0]['audit_level'] == $value['audit_level']) {
                    if ($value_level % 2 == 1) {
                        if ($role_users[0]['status'] == 1) {
                            $value['permission']  = 1;
                            $value['action_text'] = '查看';
                        } else {
                            $value['permission']  = 2;
                            $value['action_text'] = '一级审核';
                        }
                    } else {
                        if ($role_users[0]['status'] == 1) {
                            $value['permission']  = 1;
                            $value['action_text'] = '查看';
                        } else {
                            $value['permission']  = 2;
                            $value['action_text'] = '二级审核';
                        }
                    }
                } else {
                    $value['permission']  = 1;
                    $value['action_text'] = '查看';
                }
            }


            //如果流程已走完，全部为查看
            if ($value['audit_status'] == 3) {
                $value['permission']  = 1;
                $value['action_text'] = '查看';
            }

            if ($user['id'] == 1) {
                $value['permission']  = 1;
                $value['action_text'] = '查看';
            }

            $data[] = $value;
        }


        $this->assign('role_id', $user_role);
        $this->assign("results", $data);


        $this->display();
    }

    // 跳转新增页面
    public function add()
    {
        $this->display();
    }

    // 保存新建审批表单
    public function add_post()
    {
        if (IS_POST) {
            $url = U(CONTROLLER_NAME . '/' . (I('get.fun') != NULL ? I('get.fun') : 'index'));
            $this->dataCheck();
            $data = array_merge($_POST, $this->saveData());
            if ($this->deal_model->create() !== false) {
                $result = $this->deal_model->add($data);
                if ($result !== false) {
                    // 创建审批 一级流程数据
                    $history = array(
                        'table_id'        => $result,
                        'audit_status'    => 1,
                        'audit_reason'    => '新建表单',
                        'amount_in_words' => '',
                        'audit_level'     => 1
                    );
                    $data    = array_merge($history, $this->auditAdd());
                    $this->auditHistoryModel->add($data);
                    $this->saveFile($result, 14);

                    $this->success("添加成功！", $url);
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }

    // 跳转查看画面
    public function view()
    {
        // 获取基础数据
        $id      = I('get.id', 0, 'intval');
        $result  = $this->deal_model->where(array("id" => $id))->find();
        $results = $this->att_model->where(array("table_id" => $id, "belong_to" => 14))->select();
        $this->assign("results", $results);

        // 判断工程款支付报审
        if ($this->function == 'payment' && $this->subfunction == "1") {
            if ($result['audit_level'] < 4) {
                $result = array_merge($result, $this->getTotalPrice($id));
            }
            if ($result['audit_level'] > 4 && $result['audit_level'] < 6) {
                $result = array_merge($result, $this->getTotalPrice($id, 2));
            }
        }
        $this->assign("result", $result);

        $isAudit = '1';

        // 验证当前登录人是否有审批权限
        if ($result['audit_level'] == 2 && $result['add_department'] == session('deptid') && session('Role') == 3) {
            $isAudit = '2';
        } elseif ($result['audit_level'] > 2) {

            // 查询当前审批部门
            $auditdept = $this->auditFlowModel->alias("a")
                ->field("d.department_id")
                ->join(array(
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'audit_flow_dept d ON d.flow_id = a.id'
                ))
                ->where(array(
                    'a.function'    => $this->function,
                    'a.subfunction' => $this->subfunction,
                    'd.`level`'     => intval(($result['audit_level'] - 1) / 2)
                ))
                ->find();


            $user_id   = session('ADMIN_ID');
            $role_user = $this->roleuser_model
                ->where("user_id=" . $user_id . " and code_id=" . $id . " and audit_level=" . $result['audit_level'] . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")
                ->find();
            //如果在表里，证明有权限,可能是一级审核或者是二级审核

            if ($role_user) {

                $level = intval($result['audit_level']);
                //如果是当前部门操作编辑的情况
                if (
                    (
                        $auditdept['department_id'] == session("deptid") &&
                        ($role_user['status'] == 0 || $role_user['status'] == 2)
                    ) ||
                    (
                        $auditdept['department_id'] == session("deptid") &&
                        ($role_user['status'] == 0 || $role_user['status'] == 2)
                    )
                ) {
                    $isAudit = '2';
                }
            }

        }
        $this->assign("isAudit", $isAudit);
        //dump($isAudit);
        // 循环查询审核意见
        $auditLevel = $this->getAuditFlowLevel();
        //var_dump($auditLevel);die;
        $auditResult = array();
        if ($auditLevel > 2) {
            for ($i = 3; $i < $auditLevel; $i += 2) {
                $auditResult[$i] = $this->auditHistoryModel->where(array('function' => $this->function, 'subfunction' => $this->subfunction, 'audit_level' => $i, 'table_id' => $id))->order("add_time DESC")->select();
            }
        }
        $this->assign("audit", $auditResult);
        //var_dump($auditResult);
        // 判断最终状态是否为驳回
        if ($result['audit_status'] == '2') {
            // 查询驳回原因
            $returnMsg = $this->auditHistoryModel->where(array('function' => $this->function, 'subfunction' => $this->subfunction, 'table_id' => $id))->order("add_time DESC")->find();
            $this->assign("reject", $returnMsg);
        }

        $sc = M("SubcontractContent")->where("table_id = " . $id)->select();
        //dump($sc);
        $this->assign("sc", $sc);

        // 验证审批权限
        $this->display();
    }

    // 查询总报价
    public function getTotalPrice($id, $type = 1)
    {
        $where = array(
            'payment_review_id' => $id,
            'item_name'         => '总报价[一+二]',
            'is_publish'        => '1'
        );
        $price = $this->PSummary_model->field("report_construction_amount,approved_total_amount")->where($where)->find();
        if ($type == 1) {
            $result['supervision_amount']       = $price['approved_total_amount'] != NULL ? $price['approved_total_amount'] * 0.75 : 0.00;
            $result['supervision_amount_words'] = $this->number2chinese($result['supervision_amount'], true, false);
        } else {
            $result['agent_construction_amount']       = $price['approved_total_amount'] != NULL ? $price['approved_total_amount'] * 0.75 : 0.00;
            $result['agent_construction_amount_words'] = $this->number2chinese($result['agent_construction_amount'], true, false);
        }
        return $result;
    }

    // 保存审批意见
    public function audit_post()
    {
        if (!IS_POST) {
            $this->error("非法访问！");
        }
        $url = U(CONTROLLER_NAME . '/' . (I('get.fun') != NULL ? I('get.fun') : 'index'));

        $data = array_merge($_POST, $this->auditAdd());

        //当前用户
        $user = $this->users_model->where('id=' . session('ADMIN_ID'))->find();
        //当前记录
        $ee = $this->deal_model->where("id=" . $data['table_id'])->find();

        if ($this->auditHistoryModel->create() === false) {
            $this->error($this->auditHistoryModel->getError());
        }
        $result = $this->auditHistoryModel->add($data);
        if ($result === false) {
            $this->error("保存失败！");
        }

        //如果当前用户是发起公司拥有审核权限的用户
        if ($user['department_id'] == $ee['add_department'] && $user['role_id'] == 3 && $ee['audit_level'] == 2) {

            $update = array(
                'id'           => $data['table_id'],
                'audit_level'  => $data['audit_status'] == 1 ? intval($data['audit_level']) + 1 : intval($data['audit_level']) - 1,
                'audit_status' => $data['audit_status'] == 2 ? 2 : (intval($this->getAuditFlowLevel()) == intval($data['audit_level']) ? 3 : 1)
            );
            $update = array_merge($_POST, $update);
            $this->deal_model->save($update);
            $this->success("保存成功！", $url);
        } else {

            $role_user = $this->roleuser_model->where('user_id=' . session('ADMIN_ID') . " and code_id=" . $data['table_id'] . " and audit_level=" . $data['audit_level'] . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")->find();

            if (!$role_user) {
                $this->error("没有操作权限！");
            }

            //当前人员是一级审核还是二级审核
            $option_id = $role_user['option_id'];
            $r_u_l     = $role_user['audit_level'];
            //上一层审核
            $pre_audit_level = $role_user['audit_level'] - 1;

            $all_count       = $this->roleuser_model->where("code_id=" . $data['table_id'] . " and audit_level=" . $r_u_l . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")->count();
            $all_agree_count = $this->roleuser_model->where("code_id=" . $data['table_id'] . " and audit_level=" . $r_u_l . " and status=1" . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")->count();

            if ($all_count > 0 && $all_agree_count == $all_count) {
                $this->error("已经全部通过，无需再次审核！");
            }

            if ($data['audit_status'] != 1 && $data['audit_status'] != 2) {
                $this->error("操作状态非法！");
            }

            //在下面判断同意和驳回
            if ($data['audit_status'] == 1) {
                //如果同意

                $role_update = array(
                    'do_time' => time(),
                    'status'  => 1
                );
                $this->roleuser_model->where('id=' . $role_user['id'])->save($role_update);

                $after_all_agree_count = $this->roleuser_model
                    ->where("code_id=" . $data['table_id'] . " and audit_level=" . $r_u_l . " and status=1" . " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")
                    ->count();
                if ($all_count > 0 && $after_all_agree_count == $all_count) {
               
                    //如果全部同意
                    // 修改修改主表当前处理层级+1
                    $update = array(
                        'id'           => $data['table_id'],
                        'audit_level'  => intval($data['audit_level']) + 1,
                        'audit_status' => intval($this->getAuditFlowLevel()) == intval($data['audit_level']) ? 3 : 1
                    );

                    $update = array_merge($_POST, $update);
                    $this->deal_model->save($update);
                } else {
                    //如果只是自己同意
                    $update = array(
                        'id'           => $data['table_id'],
                        'audit_level'  => intval($data['audit_level']),
                        'audit_status' => 1
                    );

                    $update = array_merge($_POST, $update);
                    $this->deal_model->save($update);
                }

            } elseif ($data['audit_status'] == 2) {
                //如果驳回
                $role_update = array(
                    'do_time' => time(),
                    'status'  => 0
                );

                //当前层级审核全部初始化
                $this->roleuser_model->where('code_id=' . $data['table_id'] . " and audit_level=" . $r_u_l.  " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")->save($role_update);

                //上层审核全部初始化
                $this->roleuser_model->where('code_id=' . $data['table_id'] . " and audit_level=" . $pre_audit_level.  " and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")->save($role_update);

                $update = array(
                    'id'           => $data['table_id'],
                    'audit_level'  => intval($data['audit_level']) - 1,
                    'audit_status' => 2
                );

                $update = array_merge($_POST, $update);
                $this->deal_model->save($update);
            }
            $this->success("保存成功！", $url);
        }
    }

    public function audit_post1()
    {
        if (IS_POST) {
            $url  = U(CONTROLLER_NAME . '/' . (I('get.fun') != NULL ? I('get.fun') : 'index'));
            $data = array_merge($_POST, $this->auditAdd());
            //var_dump($data);
            if ($this->auditHistoryModel->create() !== false) {
                $result = $this->auditHistoryModel->add($data);
                if ($result !== false) {
                    // 修改修改主表当前处理层级+1
                    // ->count();
                    //
                    $update = array(
                        'id'           => $data['table_id'],
                        'audit_level'  => $data['audit_status'] == 1 ? intval($data['audit_level']) + 1 : intval($data['audit_level']) - 1,
                        'audit_status' => $data['audit_status'] == 2 ? 2 : (intval($this->getAuditFlowLevel()) == intval($data['audit_level']) ? 3 : 1)
                    );
                    $update = array_merge($_POST, $update);
                    $this->deal_model->save($update);

                    $this->success("保存成功！", $url);
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->auditHistoryModel->getError());
            }
        }
    }


    // 获取当前审批流程的总审核层级
    private function getAuditFlowLevel()
    {
        $result = $this->auditFlowModel
            ->where(array(
                'function'    => $this->function,
                'subfunction' => $this->subfunction,
            ))
            ->getField("level", true);
        return (intval(($result[0] != '' ? $result[0] : 0)) + 1) * 2;
    }


    // 审核表基础字段
    public function auditAdd()
    {
        $audit = array(
            'function'    => $this->function,
            'subfunction' => $this->subfunction,
        );
        return array_merge($audit, $this->saveData());
    }


    // 查看审核历史列表
    public function auditHistory()
    {
        $where = array(
            'a.function'    => $this->function,
            'a.subfunction' => $this->subfunction,
            'a.table_id'    => I('get.id', 0, 'intval')
        );
        $audit = $this->auditHistoryModel->alias("a")
            ->field("a.*,u.real_name,d.department_name,f.level")
            ->join(array(
                ' LEFT JOIN ' . C('DB_PREFIX') . 'users u ON a.add_user = u.id',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'department d ON a.add_department = d.id',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'audit_flow f ON f.function = \'' . $this->function . "' AND f.subfunction='" . $this->subfunction . "'"
            ))
            ->where($where)
            ->order("a.add_time ASC")
            ->select();
        $this->assign("audits", $audit);

        $this->display();
    }

    // 查询当前用户类型
    public function getUserRole()
    {
        $user = D("Common/Users")->alias("u")
            ->field("u.role_id,d.department_role as role")
            ->join(array(
                ' LEFT JOIN ' . C('DB_PREFIX') . 'department d ON d.id = u.department_id'
            ))
            ->where(array('u.id' => session("ADMIN_ID")))
            ->find();

        $this->assign('userrole', $user);
    }

    //保存 分配权限
    public function add_distribution()
    {
        $id          = $_POST['code_id'];
        $check1      = $_POST['check1'];
        $check2      = $_POST['check2'];
        $function    = $this->function;
        $subfunction = $this->subfunction;
        $code_id     = $_POST['code_id'];
        $audit_level = $_POST['level'];
        /*$num1        = count($check1);
        $num2        = count($check2);*/
        $user = $this->users_model->where('id=' . session('ADMIN_ID'))->find();

        $d_user_ids = $this->users_model->where("department_id=" . $user['department_id'])->getField('id', true);

        $is_do = $this->roleuser_model
            ->where(" code_id=" . $code_id . " and status>0 and function='" . $this->function . "' and subfunction='" . $this->subfunction . "'")
            ->where(['user_id' => ['in', $d_user_ids]])
            ->order('audit_level asc')
            ->find();

        //判断是否有人员已经操作，如果有的话无法修改
        //$is_do = $this->roleuser_model->where("code_id=" . $code_id . " and status>0"." and function='".$this->function."' and subfunction='".$this->subfunction."'")->find();
        if ($is_do) {
            $this->error("相关人员已经操作，无法修改！");
        }

        $this->roleuser_model->where('code_id=' . $code_id . " AND function='" . $this->function . "' AND subfunction='" . $this->subfunction . "' AND (audit_level=" . ($audit_level + 1) . " OR audit_level=" . ($audit_level + 2) . " )")->delete();

        $data_2 = [
            'option_id'   => 2,
            'function'    => $function,
            'subfunction' => $subfunction,
            'code_id'     => $code_id,
            'audit_level' => $audit_level + 1
        ];

        $save_data_2 = [];

        foreach ($check1 as $check) {
            $data_2['user_id'] = $check;
            array_push($save_data_2, $data_2);
        }

        $result1 = $this->roleuser_model->addAll($save_data_2);

        $data_3 = [
            'option_id'   => 3,
            'function'    => $function,
            'subfunction' => $subfunction,
            'code_id'     => $code_id,
            'audit_level' => $audit_level + 2
        ];

        $save_data_3 = [];

        foreach ($check2 as $check) {
            $data_3['user_id'] = $check;
            array_push($save_data_3, $data_3);
        }

        $result2 = $this->roleuser_model->addAll($save_data_3);

        if ($result1 && $result2) {

            $this->success("保存成功！", U(CONTROLLER_NAME . '/' . (I('get.fun') != NULL ? I('get.fun') : 'index')));
        } else {
            $this->error("保存失败！");
        }
    }

}